package com.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.demo.config.MovieFeignClient;
import com.demo.config.OrderFeignClient;
import com.demo.controller.from.MovieTicketingsFrom;
import com.demo.controller.from.SeatingOstFrom;
import com.demo.controller.from.ostentationAddFrom;
import com.demo.controller.from.ostentationListAddFrom;
import com.demo.controller.info.MovieProduct;
import com.demo.controller.info.ostentationErrorInfo;
import com.demo.exetion.MainExection;
import com.demo.model.MovieNumberSession;
import com.demo.dao.MovieNumberSessionDao;
import com.demo.model.MovieProjection;
import com.demo.model.MovieSeating;
import com.demo.model.MovieTicketing;
import com.demo.service.MovieNumberSessionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.demo.service.MovieProjectionService;
import com.demo.service.MovieSeatingService;
import com.demo.utils.CommonUtil;
import com.demo.utils.Result;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.validation.Valid;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 杨森
 * @since 2022-04-05
 */
@Service
public class MovieNumberSessionServiceImpl extends ServiceImpl<MovieNumberSessionDao, MovieNumberSession> implements MovieNumberSessionService {
    @Resource
    private MovieFeignClient movieFeignClient;

    @Resource
    private OrderFeignClient orderFeignClient;

    @Resource
    private MovieProjectionService movieProjectionService;

    @Resource
    private MovieSeatingService movieSeatingService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<MovieNumberSession> ostentation(ostentationListAddFrom ostentationListAddFrom) throws MainExection {
        //判断电影是否存在
        Result<MovieProduct> movieProductResult = movieFeignClient.selectOneMovieProduct(ostentationListAddFrom.getProductId());
        if (movieProductResult.getCode() != 200) {
            throw new MainExection(500, "不存在该电影");
        }
        if (movieProductResult.getData().getMovieShelf() == 1) throw new MainExection(500, "该电影已下架，请上架后排场");
        //判断影厅是否存在以及是否可用
        MovieProjection movieProjectionServiceById = movieProjectionService.getById(ostentationListAddFrom.getProjectionhallId());
        if (movieProjectionServiceById == null) throw new MainExection(500, "不存在该影厅");
        if (movieProjectionServiceById.getProjectionStart() == 1) throw new MainExection(500, "该影厅已关闭");
        //判断座位是否在该影厅存在以及是否可用
        //获取每次场次信息 即该场次的座位信息
        List<ostentationAddFrom> ostentation = ostentationListAddFrom.getOstentation();
        //新建集合用于存储正确的数据
        List<ostentationAddFrom> ostentationNew = new ArrayList<>();
        //新建集合用于存储错误的数据 和其错误信息
        List<ostentationErrorInfo> ostentationErrorInfos = new ArrayList<>();
        //判断影厅是否存在座位信息
        QueryWrapper<MovieSeating> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("projectionhallid", ostentationListAddFrom.getProjectionhallId());
        List<MovieSeating> list = movieSeatingService.list(queryWrapper);
        if (list == null || list.size() == 0) throw new MainExection(500, "该影厅没有关联的座位信息");
        //将查询出来的座位信息添加到集合中
        List<SeatingOstFrom> listSeatingOstFrom = new ArrayList<>();
        for (MovieSeating movieSeating : list) {
            SeatingOstFrom seatingOstFrom = new SeatingOstFrom();
            seatingOstFrom.setColumns(movieSeating.getColumns());
            seatingOstFrom.setRowNumber(movieSeating.getRownumber());
            listSeatingOstFrom.add(seatingOstFrom);
        }
        //将所有时间存入一个list集合
        List<String> liststring = new ArrayList<>();
        //判断排场 和座位信息是否正常
        for (ostentationAddFrom ostentationAddFrom : ostentation) {
            boolean bool = true;
//            QueryWrapper<MovieNumberSession> queryWrapper1=new QueryWrapper<>();
//            queryWrapper1.eq("Screening_time",ostentationAddFrom.getScreeningTime());
//            queryWrapper1.eq("end_time",ostentationAddFrom.getEndTime());
//            List<MovieNumberSession> movieNumberSessions = baseMapper.selectList(queryWrapper1);
//            if (movieNumberSessions!=null || movieNumberSessions.size()>0){
//                bool=false;
//            }
            //判断时间是否重合
            if (liststring == null || liststring.size() == 0) {
                String Screening = CommonUtil.dataLocalDate(ostentationAddFrom.getScreeningTime());
                String end = CommonUtil.dataLocalDate(ostentationAddFrom.getEndTime());
                String s = Screening + "--" + end;
                liststring.add(s);
            } else {
                //排序之后输入
                SimpleDateFormat formater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                //本次的时间
                String Screening = CommonUtil.dataLocalDate(ostentationAddFrom.getScreeningTime());
                String end = CommonUtil.dataLocalDate(ostentationAddFrom.getEndTime());
                String s = Screening + "--" + end;
                String[] date2 = s.split("--");
                Date startdate2 = null;
                Date enddate2 = null;
                boolean a = false;
                try {
                    startdate2 = formater.parse(date2[0]);
                    enddate2 = formater.parse(date2[1]);
                } catch (ParseException e) {
                    e.printStackTrace();
                }

                //先把所有时间进行排序
                Collections.sort(liststring);
                try {
                    for (int i = 0; i < liststring.size(); i++) {
                        String[] date1 = liststring.get(i).split("--");
                        Date startdate1 = formater.parse(date1[0]);
                        Date enddate1 = formater.parse(date1[1]);
                        if (startdate2.getTime()>enddate1.getTime() ||enddate2.getTime()< startdate1.getTime()) {
                            //没有重叠
                            a = true;
                        } else {
                            //有重叠不添加
                            System.out.println("本次新增有重叠");
                            bool = false;
                        }
                        // 不让自己和自己进行比较，j从i的下一个开始
//                        for (int j =i+1;j<liststring.size();j++){
//                            String[] date2 = liststring.get(j).split("--");
//                            Date startdate2 = formater.parse(date2[0]);
//                            Date enddate2 = formater.parse(date2[1]);
//                            if(startdate1.before(startdate2) && enddate1.after(startdate2)){
//                                System.out.println(liststring.get(i)+"与"+liststring.get(j)+"有重叠");
//                            }
//                        }
                    }
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                if (a){
                    liststring.add(s);
                }
            }
            //判断票价是否合理
            String price = ostentationAddFrom.getPrice();
            double v = Double.parseDouble(price);
            if (v <= 0) {
                bool = false;
                ostentationErrorInfos.add(ostentationErrorInfo.builder().ostentation(ostentationAddFrom).message("该场次的票价不合理").build());
            }
            List<SeatingOstFrom> seatingList = ostentationAddFrom.getSeatingList();
            //判断座位信息是否符合
            for (SeatingOstFrom seatingOstFrom : seatingList) {
                boolean contains = listSeatingOstFrom.contains(seatingOstFrom);
                if (contains == false) {
                    bool = false;
                    ostentationErrorInfos.add(ostentationErrorInfo.builder().ostentation(ostentationAddFrom).message("该场次的座位：第" + seatingOstFrom.getRowNumber() + "排，第" + seatingOstFrom.getColumns() + "在影厅中不存在").build());
                    break;
                }
                continue;
            }
            if (bool) {
                //将座位筛选通过的场次信息存入新集合
                ostentationNew.add(ostentationAddFrom);
            }
        }
        //新增成功的集合
        List<MovieNumberSession> movieNumberSessions = new ArrayList<>();
        //将新增场次中的场次信息和座次信息循环录入
        List<MovieTicketing> movieTicketings = new ArrayList<>();
        for (ostentationAddFrom ostentationAddFrom : ostentationNew) {
            //新增场次
            MovieNumberSession movieNumberSession = CommonUtil.copyOne(ostentationAddFrom, MovieNumberSession.class);
            movieNumberSession.setMovieName(movieProductResult.getData().getMovieTitle());
            movieNumberSession.setProductId(movieProductResult.getData().getProductId());
            movieNumberSession.setMovieType(movieProductResult.getData().getMovieType());
            movieNumberSession.setMovieImgurl(movieProductResult.getData().getMovieImgurl());
            movieNumberSession.setCreateTime(CommonUtil.dataLocalDatePares());
            movieNumberSession.setStart(0);
            movieNumberSession.setProjectionhallId(ostentationListAddFrom.getProjectionhallId());
            Integer integer = baseMapper.addMovieNumber(movieNumberSession);
            if (integer <= 0) throw new MainExection(500, "新增场次信息错误");
            movieNumberSessions.add(movieNumberSession);
            //根据场次生成的主键id 生成票务信息.
            List<SeatingOstFrom> seatingList = ostentationAddFrom.getSeatingList();
            for (SeatingOstFrom seatingOstFrom : seatingList) {
                MovieTicketing movieTicketing = CommonUtil.copyOne(seatingOstFrom, MovieTicketing.class);
                movieTicketing.setScreeningTime(movieNumberSession.getScreeningTime());
                movieTicketing.setEndTime(movieNumberSession.getEndTime());
                movieTicketing.setProjectionhallId(movieNumberSession.getProjectionhallId());
                movieTicketing.setProductId(movieNumberSession.getProductId());
                movieTicketing.setMovieName(movieNumberSession.getMovieName());
                movieTicketing.setCreateTime(CommonUtil.dataLocalDatePares());
                movieTicketing.setRownumber(seatingOstFrom.getRowNumber());
                movieTicketing.setNumberOfSessionsId(movieNumberSession.getNumberOfSessionsId());
                movieTicketing.setPrice(movieNumberSession.getPrice());
                movieTicketings.add(movieTicketing);
            }
        }
//        if (movieTicketings ==null ||movieTicketings.size()==0)throw new MainExection(500, "为存在有效数据");
        MovieTicketingsFrom movieTicketingsFrom = new MovieTicketingsFrom();
        movieTicketingsFrom.setMovieTicketings(movieTicketings);
        Result<Boolean> booleanResult = orderFeignClient.addMovieTicketings(movieTicketingsFrom);
        if (booleanResult.getData() == false) throw new MainExection(500, "新增票务信息失败");
        return movieNumberSessions;
    }
}
